<?php
/**
 * Created by PhpStorm.
 * User: Jie
 * Date: 4/1/2016
 * Time: 10:16 AM
 */
class wechatCallbackapi
{
    public $myToken = null;
    public function valid(){
        $echoStr = $_GET["echostr"];
        $config = \Yaf_Registry::get('configarr');
        $this->myToken = $config['wechat']['myToken'];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
        exit;
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : '';

        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            //实例化xml对象
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            //准备消息内容
            //消息发送者
            $fromUsername = $postObj->FromUserName;
            //消息接收者
            $toUsername = $postObj->ToUserName;
            //接收消息内容
            $keyword = trim($postObj->Content);
            //接受信息事件
            $event = '';
            $event = isset($postObj->Event) ? $postObj->Event : '';
            $eventkey = isset($postObj->EventKey) ? $postObj->EventKey : '';

            //调用方法，将用户消息写入数据库
            $record_res = $this->messageDbWrite($postObj);


            //当前时间
            $time = time();
            //文本消息模板
            $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[Text]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
            //图片消息
            $picTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[image]]></MsgType>
						<Image>
						<MediaId><![CDATA[%s]]></MediaId>
						</Image>
						</xml>";
            //语音消息
            $vioceTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[voice]]></MsgType>
							<Voice>
							<MediaId><![CDATA[%s]]></MediaId>
							</Voice>
							</xml>";
            //图文消息
            $newsHTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[news]]></MsgType>
                        <ArticleCount>%s</ArticleCount>
                        <Articles>";
            $newsCTpl = "<item>
                        <Title><![CDATA[%s]]></Title>
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>";
            $newsTTpl = "</Articles>
                        </xml> ";

            //用户首次关注事件
            if($event == 'subscribe') {
                $contentStr = "感谢关注大发搬家服务公司公众号，联系电话：020-36228228。请多关注我们的优惠活动。";
                //按格式输出
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $contentStr);
                //输出结果
                echo $resultStr;
            }

            //用户点击事件
            if($event == 'CLICK') {
                if($eventkey == 'eventtest01') {
                    $newsContent = '';
                    //回复图文消息
                    $pic_arr = array(
                        'http://img0.pconline.com.cn/pconline/1603/29/7718220_4.jpg',
                        'http://img0.pconline.com.cn/pconline/1603/29/7718220_6.jpg',
                        'http://img0.pconline.com.cn/pconline/1603/29/7718220_7.jpg',
                    );
                    foreach($pic_arr as $k => $v) {
                        $newsContent .= sprintf($newsCTpl, $k, 'xxx',$v ,'www.baidu.com');
                    }
                    //文章数量
                    $newsCount = count($pic_arr);
                    //按格式输出
                    $resultStr = sprintf($newsHTpl . $newsContent . $newsTTpl, $fromUsername, $toUsername, $time, $newsCount);
                    //输出结果
                    echo $resultStr;
                } else {
                    $contentStr = "没有定义此事件";
                    //按格式输出
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $contentStr);
                    //输出结果
                    echo $resultStr;
                }
            }

            //关键词不为空
            if(!empty( $keyword ))
            {
                //回复信息类型
                //$msgType = "text";

                //判断不同的关键词应答
                if($keyword == '价格') {
                    //回复内容
                    $contentStr = "服务价格是xxxx";
                } elseif($keyword == '最新活动') {
                    $contentStr = "最新的优惠活动有
						1xxxx
						2xxxxxx
						3xxxxbb
						4cccccc";
                } elseif($keyword == '预约服务') {
                    $contentStr = "在线预约有
						1xxxx
						2xxxxxx
						3xxxxbb
						4cccccc";
                } else {
					$contentStr = "麻烦请输入关键字(价格活动预约)，再进行回答，谢谢";
				}
                //按格式输出
                //$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $contentStr);
                //输出结果
                echo $resultStr;
            }else{
                echo "请输入内容，谢谢";
            }

        }else {
            echo "";
            exit;
        }
    }

    //用于验证签名的方法
    private function checkSignature(){
        // you must define TOKEN by yourself
        if (!$this->myToken) {
            die('token is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $tmpArr = array($this->myToken, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    //用于将消息写入数据库
    public function messageDbWrite($dataObj) {
        $messageModel = new WxmessageModel();
        //读取详细信息
        $fUser = $dataObj->FromUserName;
        $tUser = $dataObj->ToUserName;
        $cTime = $dataObj->CreateTime;
        $mType = $dataObj->MsgType;

        //消息文本内容
        $mContent = isset($dataObj->Content) ? $dataObj->Content : '';
        //图片
        $mPicUrl = isset($dataObj->PicUrl) ? $dataObj->PicUrl : '';
        //媒体id
        $mMediaId = isset($dataObj->MediaId) ? $dataObj->MediaId : '';
        //语音格式
        $mFormat = isset($dataObj->Format) ? $dataObj->Format : '';
        //语音识别
        $mRecognition = isset($dataObj->Recognition) ? $dataObj->Recognition : '';
        //视频缩略图id
        $mThumbMediaId = isset($dataObj->ThumbMediaId) ? $dataObj->ThumbMediaId : '';
        //消息标题
        $mTitle = isset($dataObj->Title) ? $dataObj->Title : '';
        //消息描述
        $mDescription = isset($dataObj->Description) ? $dataObj->Description : '';
        //消息链接
        $mUrl = isset($dataObj->Url) ? $dataObj->Url : '';
        //微信平台消息id
        $mId = $dataObj->MsgId;

        //组织正常的数据
        $data = array(
            'mfromusername' => $fUser,
            'mtousername' => $tUser,
            'mcreatetime' => $cTime,
            'mtype' => $mType,
            'mcontent' => $mContent,
            'mpicurl' => $mPicUrl,
            'mmediaid' => $mMediaId,
            'mformat' => $mFormat,
            'mthumbmediaid' => $mThumbMediaId,
            'mtitle' => $mTitle,
            'mdescription' => $mDescription,
            'murl' => $mUrl,
            'mid' => $mId,
            'mstate' => 0,
        );

        //写入数据库
        return $messageModel->recordUserMessage($data);
    }
}